
var _lastline = "";
var _debug_container_name;

function initDebug(selector, done) {
	//cprint("init debug");

	_debug_container_name = selector;

	cprint("init debug: " + _debug_container_name);

	
	$(_debug_container_name).load("html/debug.html", initConsole);
	$(_debug_container_name).addClass("debug_container");

	
	//initConsole();
	
	//$(_debug_container_name).hide();

}

function initConsole() {
		
	/*
	$(_debug_container_name + " .debug_toggle").each(function() {
		$(this).click(function() {
			//cprint("toggle click");
			$(this).siblings("div[id*=_body]").toggle();
		});
	});
	*/
	
	$("#console_input").each(function() {
		$(this).keypress(function (e) {
		
			if (e.keyCode == 13) {
				
				var line = $(_debug_container_name + " #console_input input").val();
				cprint(">" + line);	
				
				if (line == "") { line = _lastline; }
				else { lastline = line; }
				
				//cprint($("#console_input input").val());
				evalConsoleLine(line);
				$(_debug_container_name + " #console_input input").val("");
				
			}
		});
	});
	
	$(document).keydown(function(e) {
		//cprint(e.keyCode);
		if (e.keyCode == 192) {
			$(_debug_container_name).toggle();
			$(_debug_container_name + " #console_input input").focus();
			return false; // trap keypress so does not bubble up
		}
	});
	
	$(_debug_container_name).draggable( { handle: '.debug_toggle' } );
	
	//$("#console_body").toggle();
	
	cprint("Console loaded...");
	
	initApp();
}

function cprint(line, color) {
	
	if (window.location.hash == "#console") {
		var output = $("#console_output");
		if (color == undefined) {
			output.append("<p>"+line+"</p>"); 
		} else {
			output.append("<p style='color: "+color+";'>"+line+"</p>");
		}
		output.attr({ scrollTop: output.attr("scrollHeight") });
	}
}